//
//  BookmarkViewController.m
//  We365
//
//  Created by Pham Khuong Duy on 1/13/12.
//  Copyright 2012 __MyCompanyName__. All rights reserved.
//

#import "BookmarkViewController.h"
#import "BusinessViewController.h"

@implementation BookmarkViewController
@synthesize table;
@synthesize search;
@synthesize bookmark;

int selectedRow = -1;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

- (void)viewDidLoad
{
    [super viewDidLoad];
    bookmark = [[Bookmark alloc] init];
    [bookmark getAllFavourites];
    
    UIBarButtonItem *edit = [[UIBarButtonItem alloc] initWithTitle:@"Delete" style:UIBarButtonItemStyleBordered target:self action:@selector(edit:)];
    self.navigationItem.rightBarButtonItem = edit;
    [edit release];
    
    // Search
    search.delegate = self;
    [[[search subviews] objectAtIndex:0] removeFromSuperview];
    search.tintColor = [UIColor colorWithRed:53.0f/255.0f green:91.0f/255.0f blue:0.0f alpha:1.0f]; 
    
    self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:BGSearch]];
    
    [table reloadData];
    // Do any additional setup after loading the view from its nib.
}

- (void)viewDidUnload
{
    [self setTable:nil];
    [self setSearch:nil];
    [self setBookmark:nil];
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (void)viewWillAppear:(BOOL)animated
{
    if(selectedRow == -1)
        return;
    
    [bookmark getAllFavourites];
    [table reloadData];
    [super viewWillAppear:animated];
}

- (void)viewWillDisappear:(BOOL)animated
{
    int count = [self.navigationController.viewControllers count];
    if ([self.navigationController.viewControllers indexOfObject:self] == NSNotFound) {
        NSLog(@"View will disappear loading...count:");
        NSLog(@"%d",count);
        if (count == 1) {
            NSLog(@"Main View Will Display");
            NSLog(@"goBack function");
            [UIView beginAnimations:@"animation" context:nil];
            [UIView setAnimationDuration:1.0];
            [UIView setAnimationCurve:UIViewAnimationCurveEaseIn];
            [UIView setAnimationTransition:UIViewAnimationTransitionCurlDown forView:self.navigationController.view cache:NO];
            [self.navigationController popViewControllerAnimated:NO];
            [UIView commitAnimations];
            
        }
        else {
            NSLog(@"Not Found View Main");
        }
    }
    
    search.text = @"";
    [search resignFirstResponder];
    search.showsCancelButton = NO;
    [super viewWillDisappear:animated];
}

- (NSString *)title
{
    return @"Favorite";
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

- (void)dealloc {
    [table release];
    [search release];
    [bookmark release];
    [super dealloc];
}

- (IBAction)edit:(id)sender
{
    [self.table setEditing:!self.table.editing animated:YES];
    if (self.table.editing) [self.navigationItem.rightBarButtonItem setTitle:@"Done"];
    else
        [self.navigationItem.rightBarButtonItem setTitle:@"Delete"];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return [bookmark.list count];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *cellIdentifier = @"Cell";
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
    if(cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease];
        cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    
    int row = [indexPath row];
    Item *item = [bookmark.list objectAtIndex:row];
    
    
    cell.textLabel.text = item.ItemName;
    
    if (row % 2 == 0) {
        UIColor *colorEven = [UIColor colorWithRed:0.0f/255.0f green:168.0f/255.0f blue:255.0f/255.0f alpha:1.0f];
        cell.textLabel.textColor = colorEven;
        cell.textLabel.shadowColor = [UIColor whiteColor];
        cell.textLabel.shadowOffset = CGSizeMake(1, 0.8f);
    }
    else {
        UIColor *colorOdd = [UIColor colorWithRed:255.0f/255.0f green:90.0f/255.0f blue:0.0f/255.0f alpha:1.0f];
        cell.textLabel.textColor = colorOdd;
        cell.textLabel.shadowColor = [UIColor yellowColor];
        cell.textLabel.shadowOffset = CGSizeMake(1, 0.8f);
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    selectedRow = row;
    Item *item = [bookmark.list objectAtIndex:row];
    BusinessViewController *business = [[BusinessViewController alloc] initWithItem:item];
    [self.navigationController pushViewController:business animated:YES];
    [business release];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    int row = [indexPath row];
    Item *item = [bookmark.list objectAtIndex:row];
    [bookmark removeFavourite:item.ItemID];
    [self.bookmark.list removeObjectAtIndex:row];    
    [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [table reloadData];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (indexPath.row%2) {
        cell.backgroundColor = [UIColor clearColor];
        
    }
    else {
        // 192-200-214
        cell.backgroundColor = [UIColor colorWithRed:217.0f/255.0f green:228.0f/255.0f blue:249.0f/255.0f alpha:1.0f];
        
    }
}

- (void)resetSearch
{
    [bookmark getAllFavourites];
}

- (void)handleSearch:(NSString *)keyword
{
    [self resetSearch];
    NSMutableArray *toRemove = [[NSMutableArray alloc] init];
    for (Item *item in bookmark.list) {
        if([item.ItemName rangeOfString:keyword options:NSCaseInsensitiveSearch].location == NSNotFound)
            [toRemove addObject:item];
    }
    [bookmark.list removeObjectsInArray:toRemove];
    [table reloadData];
    [toRemove release];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText
{
    if([searchText length] == 0)
    {
        [self resetSearch];
        [table reloadData];
        return;
    }
    [self handleSearch:searchText];
}

- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar
{
    [search setShowsCancelButton:YES animated:YES];
}

- (void)searchBarCancelButtonClicked:(UISearchBar *)searchBar
{
    search.text = @"";
    [self resetSearch];
    [table reloadData];
    [search resignFirstResponder];
    [search setShowsCancelButton:NO animated:YES];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    [self handleSearch:[searchBar text]];
    [search resignFirstResponder];
    [search setShowsCancelButton:NO animated:YES];
}
@end
